package com.zmn.oms.admin.controller.common;

import com.alibaba.fastjson.JSON;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.common.dto.categ.CategProductGroupDRO;
import com.zmn.base.product.common.dto.product.ec.DefaultEcProductQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.common.query.categ.CategProductGroupQuery;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductGroupForeignListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.dto2.OptionData;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.admin.controller.order.OrderBaseController;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.bo.product.ProductBO;
import com.zmn.oms.model.dto.common.OrderProductGroupQuery;
import com.zmn.oms.model.dto.common.ServCategQuery;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.dto.product.ProductQueryDTO;
import com.zmn.oms.model.dto.work.CheckRepeatProductDTO;
import com.zmn.oms.model.dto.work.modify.BackProductPriceQueryDTO;
import com.zmn.oms.model.dto.work.modify.BackProductPriceResultDTO;
import com.zmn.oms.model.vo.product.OrderProductGroupVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：产品相关
 *
 * @author liuying
 * @date 2018/11/21 15:36
 */
@Slf4j
@Controller
@RequestMapping("/serv")
public class ServController extends OrderBaseController {

    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected ProductGroupForeignListRemoteService productGroupForeignListRemoteService;
    @Autowired
    private ServItemBService servItemBService;

    /**
     * 查询服务分类
     *
     * @return
     */
    @RequestMapping(value = "category/list")
    @ResponseBody
    public ResultDTO categoryList() {
        return ResultDTO.success(super.getShowServCategList());
    }

    /**
     * 查询二级产品分类 (zmn select 使用)
     * @param query   服务分类
     * @return
     */
    @PostMapping(value = "categ/categOne/list")
    @ResponseBody
    public ResultDTO categOneList(@RequestBody ServCategQuery query) {
        List<KVDict> vtList = super.getOneCategoryList(query.getServCategId(), query.getShowType());
        return ResultDTO.success(vtList);
    }

    /**
     * 查询二级产品分类 (zmn select 使用)
     * @param query   服务分类
     * @return
     */
    @PostMapping(value = "categ/categTwo/list")
    @ResponseBody
    public ResultDTO categTwoList(@RequestBody ServCategQuery query) {
        List<KVDict> vtList;
        if (query.getCategIdList() == null) {
            vtList = super.getTwoCategoryList(query.getServCategId(), query.getShowType());
        } else if (NumberUtil.isNullOrZero(query.getServCategId())) {
            vtList = super.getTwoCategoryList(query.getCategIdList(), query.getShowType());
        } else {
            vtList = super.getTwoCategoryList(query.getServCategId(), query.getCategIdList(), query.getShowType());
        }
        return ResultDTO.success(vtList);
    }

    /**
     * 通过城市和渠道查询服务分类
     *
     * @return
     */
    @RequestMapping(value = "category/listByCityIdAndChannelIdAndShowType", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO listByCityIdAndChannelId(@RequestParam("channelId")Integer channelId, @RequestParam("cityId") Integer cityId, @RequestParam(value = "showType", defaultValue = "1") Integer showType) {
        return ResultDTO.success(super.getServCategByChannelIdAndShowTypeAndCityId(channelId, showType, cityId));
    }

    /**
     * 查询二级产品分类
     *
     * @param servCategId   服务分类
     * @param categOneIdList 一级分类集合
     * @return
     */
    @RequestMapping(value = "categ/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO categoryList(@RequestParam(value = "servCategId") Integer servCategId, @RequestParam(value = "categOneIdList[]", required = false) Integer[] categOneIdList, @RequestParam(value = "productShowType", defaultValue = "1") Integer productShowType) {
        List<KVDict> vtList;
        if (categOneIdList == null) {
            vtList = super.getTwoCategoryList(servCategId, productShowType);
        } else if (NumberUtil.isNullOrZero(servCategId)) {
            vtList = super.getTwoCategoryList(Arrays.asList(categOneIdList), productShowType);
        } else {
            vtList = super.getTwoCategoryList(servCategId, Arrays.asList(categOneIdList), productShowType);
        }
        return ResultDTO.success(vtList);
    }

    /**
     * 查询一级产品分类
     *
     * @param servCategId   服务分类
     * @param showType 一级分类集合
     * @return
     */
    @RequestMapping(value = "categOne/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO categoryList(@RequestParam(value = "servCategId") Integer servCategId, @RequestParam(value = "showType", defaultValue = "1") Integer showType) {
        List<KVDict> vtList = super.getOneCategoryList(servCategId, showType);
        return ResultDTO.success(vtList);
    }

    /**
     * 查询服务分类级别
     *
     * @param servCategId   服务分类
     * @param oneCategoryId 一级分类
     * @return
     */
    @RequestMapping(value = "category/base/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO baseTwoCategoryList(@RequestParam(value = "servCategId") Integer servCategId, @RequestParam(value = "oneCategoryId", required = false) Integer oneCategoryId, @RequestParam(value = "productShowType", defaultValue = "1") Integer productShowType) {
        List<KVDict> vtList;
        if (oneCategoryId == null) {
            vtList = super.getTwoCategoryList(servCategId, productShowType);
        } else {
            vtList = super.getTwoCategoryList(servCategId, Arrays.asList(oneCategoryId), productShowType);
        }
        return ResultDTO.success(vtList);
    }

    /**
     * 通过服务分类获取产品列表
     *
     * @param queryDTO
     * @return
     */
    @RequestMapping(value = "product/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO productList(ProductQueryDTO queryDTO) {
        queryDTO.setShowType(Optional.ofNullable(queryDTO.getShowType()).orElse(BaseProductConsts.ERP_SHOW_TYPE));
        queryDTO.setIncludeDisabled(Optional.ofNullable(queryDTO.isIncludeDisabled()).orElse(false));

        logger.debug("#productList 入参：{}", JSON.toJSONString(queryDTO));

        List<KVDict> servProductList = super.getServProductList(queryDTO);

        if (StringUtils.isNotBlank(queryDTO.getRequestId())) {
            logger.info("#productList requestId={} 入参{} ", queryDTO.getRequestId(), JSON.toJSONString(servProductList));
        }

        // 获取禁用前台产品关联的后台产品
//        if (Objects.equals(queryDTO.getShowType(), BaseProductConsts.EC_SHOW_TYPE)) {
//            servProductList.addAll(super.getServProductListByDisableShowProduct(queryDTO));
//        }

        return ResultDTO.success(servProductList);
    }

    /**
     * 模糊获取产品列表
     *
     * @param queryDTO
     * @return
     */
    @RequestMapping(value = "/fuzzy/product/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO fuzzyProductList(ProductQueryDTO queryDTO) {
        queryDTO.setShowType(Optional.ofNullable(queryDTO.getShowType()).orElse(BaseProductConsts.ERP_SHOW_TYPE));
        queryDTO.setIncludeDisabled(Optional.ofNullable(queryDTO.isIncludeDisabled()).orElse(false));
        List<KVDict> servProductList = super.getServProductList(queryDTO);
        return ResultDTO.success(servProductList);
    }

    /**
     * 通过产品二级分类获取产品列表
     * @param queryDTO
     * @return
     */
    @RequestMapping(value = "bycategid/product/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO productListByCategId(ProductQueryDTO queryDTO) {
        queryDTO.setShowType(Optional.ofNullable(queryDTO.getShowType()).orElse(BaseProductConsts.ERP_SHOW_TYPE));
        queryDTO.setIncludeDisabled(Optional.ofNullable(queryDTO.isIncludeDisabled()).orElse(false));
        return ResultDTO.success(super.getServProductListByCategId(queryDTO));
    }

    /**
     * 通过产品获取故障信息
     *
     * @param productId 产品ID
     * @return
     */
    @RequestMapping(value = "product/subsidiary/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO subsidiaryList(int productId) {
        return ResultDTO.success(super.getSubsidiaryList(productId));
    }

    /**
     * 品牌
     *
     * @return
     */
    @RequestMapping(value = "brand/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO brandList() {
        return ResultDTO.success(super.getBrandList());
    }

    /**
     * 产品分组
     *
     * @return
     */
    @RequestMapping(value = "product/group/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO productGroupList(int bizType) {
        ResponseDTO<OptionData<Integer>> responseDTO = productGroupForeignListRemoteService.listOptionByBizTypeList(Lists.newArrayList(bizType), GlobalConsts.YES);
        if (Objects.isNull(responseDTO.getData())) {
            return ResultDTO.success(Collections.EMPTY_LIST);
        }
        if (CollectionUtil.isNullOrEmpty(responseDTO.getData().getOptions())) {
            return ResultDTO.success(Collections.EMPTY_LIST);
        }
        List<VtDTO> vtDTOList = responseDTO.getData().getOptions()
                .stream()
                .map(e -> new VtDTO(e.getValue(), e.getLabel(), e.getDisabled()))
                .collect(Collectors.toList());

        return ResultDTO.success(vtDTOList);
    }

    /**
     * 校验购物车产品是否重复
     * @param checkRepeatProductDTO
     * @return
     */
    @PostMapping("/check/repeat/product")
    @ResponseBody
    public ResultDTO checkRepeatProduct(@RequestBody CheckRepeatProductDTO checkRepeatProductDTO){
        List<OrderProductDTO> list = checkRepeatProductDTO.getProductList();
        if (list.size() == 1){
            return ResultDTO.success();
        }
        // 拿到最后一个产品，最后一个是新选择的产品
        OrderProductDTO newProduct = list.get(list.size() - 1);

        // 最后一个产品和其他产品比较
        for (int i = 0; i < list.size() - 1; i++){

            // 前台产品
            if (Objects.nonNull(newProduct.getShowProductId())){
                if (Objects.nonNull(list.get(i).getShowProductId())){
                    if (Objects.equals(list.get(i).getShowProductId(), newProduct.getShowProductId())){
                        return ResultDTO.fail("产品重复");
                    }
                    continue;
                }

                // 通过前台产品查询后台产品
                BackProductPriceQueryDTO build = BackProductPriceQueryDTO
                        .builder()
                        .platWork(checkRepeatProductDTO.getPlatWork())
                        .showProductId(newProduct.getShowProductId())
                        .cityId(checkRepeatProductDTO.getCityId())
                        .channelId(checkRepeatProductDTO.getChannelId())
                        .brandId(checkRepeatProductDTO.getBrandId())
                        .bizType(checkRepeatProductDTO.getBizType())
                        .build();
                BackProductPriceResultDTO backProductPriceResultDTO = servItemBService.queryBackProductPrice(build);
                if (Objects.isNull(backProductPriceResultDTO)){
                    continue;
                }

                // 如果有后台产品
                if (Objects.equals(backProductPriceResultDTO.getProductId(), list.get(i).getProductId())) {
                    return ResultDTO.fail("产品重复");
                }
                continue;
            }

            // 后台产品
            if (Objects.nonNull(list.get(i).getProductId())) {
                if (Objects.equals(list.get(i).getProductId(), newProduct.getProductId())) {
                    return ResultDTO.fail("产品重复");
                }
                continue;
            }

            // 通过后台产品查询前台产品
            DefaultEcProductQuery defaultEcProductQuery = new DefaultEcProductQuery();
            defaultEcProductQuery.setProductIdList(Lists.newArrayList(newProduct.getProductId()));
            defaultEcProductQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);
            ResponseDTO<List<ProductBaseDRO>> listResponseDTO = productForeignListRemoteService.listEcErpProductByQuery(defaultEcProductQuery);
            List<ProductBaseDRO> showProductList = listResponseDTO.getData();
            if (CollectionUtil.isNullOrEmpty(showProductList)){
                continue;
            }
            // 如果后台产品查到的前台产品跟集合的前台产品相同，则查询前台产品的后台产品集合
            if (Objects.equals(list.get(i).getShowProductId(), showProductList.get(0).getProductId())){
                // 通过前台产品查询后台产品
                BackProductPriceQueryDTO build = BackProductPriceQueryDTO
                        .builder()
                        .platWork(checkRepeatProductDTO.getPlatWork())
                        .showProductId(list.get(i).getShowProductId())
                        .cityId(checkRepeatProductDTO.getCityId())
                        .channelId(checkRepeatProductDTO.getChannelId())
                        .brandId(checkRepeatProductDTO.getBrandId())
                        .bizType(checkRepeatProductDTO.getBizType())
                        .build();
                BackProductPriceResultDTO backProductPriceResultDTO = servItemBService.queryBackProductPrice(build);
                if (Objects.isNull(backProductPriceResultDTO)){
                    continue;
                }
                // 如果后台产品只有一个
                if (Objects.equals(backProductPriceResultDTO.getProductId(), newProduct.getProductId())) {
                    return ResultDTO.fail("产品重复");
                }
            }
        }

        return ResultDTO.success();

    }

    /**
     * 根据产品信息获取对应产品组信息
     *
     * @param orderProductGroupQuery
     * @return
     */
    @GetMapping("/product/group/getCategProductGroup")
    @ResponseBody
    public ResultDTO getCategProductGroup(OrderProductGroupQuery orderProductGroupQuery) {
        ProductBO showProductBO = new ProductBO();
        ProductBO productBO = new ProductBO();
        if (NumberUtil.isNotNullOrZero(orderProductGroupQuery.getShowProductId())) {
            showProductBO = this.getShowProductByProductId(orderProductGroupQuery.getShowProductId());
        }
        if (NumberUtil.isNotNullOrZero(orderProductGroupQuery.getProductId())) {
            productBO = this.getProductByProductId(orderProductGroupQuery.getProductId());

            // 设置前台产品
            showProductBO = this.getShowProductByProductId(orderProductGroupQuery.getProductId());
        }
        if (NumberUtil.isNotNullOrZero(productBO.getCategId())) {
            // 后台产品分组
            logger.debug("servAssCategoryListRemoteService#getProductGroupByCategId 查询产品分组 入参：servCateg={}, categTwoId={}", orderProductGroupQuery.getServCategId(), productBO.getCategId());
            CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
            categProductGroupQuery.setBizType(orderProductGroupQuery.getBizType());
            categProductGroupQuery.setServCategId(orderProductGroupQuery.getServCategId());
            categProductGroupQuery.setCategId(productBO.getCategId());
            categProductGroupQuery.setShowType(BaseProductConsts.ERP_SHOW_TYPE);
            ResponseDTO<CategProductGroupDRO> categoryProductGroupDROResponseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(categProductGroupQuery);
            logger.debug("servAssCategoryListRemoteService#getProductGroupByCategId 查询产品分组 出参：【{}】", categoryProductGroupDROResponseDTO);
            CategProductGroupDRO categorySimpleProductGroupDRO = categoryProductGroupDROResponseDTO.getData();
            if (categorySimpleProductGroupDRO != null) {
                OrderProductGroupVo orderProductGroupVo = BeanMapper.map(categorySimpleProductGroupDRO, OrderProductGroupVo.class);
                return ResultDTO.success(orderProductGroupVo);
            }
        } else if (NumberUtil.isNotNullOrZero(showProductBO.getCategId())) {
            // 前台产品分组
            logger.debug("servAssCategoryListRemoteService#getProductGroupByShowCategId 查询产品分组 入参：servCateg={}, categTwoId={}", orderProductGroupQuery.getServCategId(), showProductBO.getCategId());
            CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
            categProductGroupQuery.setBizType(orderProductGroupQuery.getBizType());
            categProductGroupQuery.setServCategId(orderProductGroupQuery.getServCategId());
            categProductGroupQuery.setCategId(showProductBO.getCategId());
            categProductGroupQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);
            ResponseDTO<CategProductGroupDRO> responseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(categProductGroupQuery);
            logger.debug("servAssCategoryListRemoteService#getProductGroupByShowCategId 查询产品分组 出参：【{}】", responseDTO);
            CategProductGroupDRO categorySimpleProductGroupDRO = responseDTO.getData();
            if (categorySimpleProductGroupDRO != null) {
                OrderProductGroupVo orderProductGroupVo = BeanMapper.map(categorySimpleProductGroupDRO, OrderProductGroupVo.class);
                return ResultDTO.success(orderProductGroupVo);
            }
        }
        return ResultDTO.fail("获取产品组信息失败");
    }

}
